extends Sprite2D

var speed = 0.1
var last_dir: Vector2
var moving = false
@export var grid:TileMapLayer

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	pass # Replace with function body.

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	var curpos = self.position
	var offset = Vector2(0,0)
	if Input.is_action_pressed("up_move"):
		offset.y -= 10 * speed
	elif  Input.is_action_pressed("down_move"):
		offset.y += 10 * speed
	elif  Input.is_action_pressed("left_move"):
		offset.x -= 10 * speed
	elif  Input.is_action_pressed("right_move"):
		offset.x += 10 * speed
	var cell = grid.local_to_map(position+offset)
	
	moving = false
	if grid.get_cell_source_id(cell) != -1:
		if offset != Vector2.ZERO:
			self.position += offset
			moving = true
	#print("地块信息："+str(grid.get_cell_source_id(cell)))

	var direction = (global_position - curpos).normalized()
	if(direction != Vector2.ZERO and direction != last_dir):
		if direction.x > 0:
			$AnimationPlayer.play("18_right")
		elif direction.x < 0:
			$AnimationPlayer.play("18_left")
		elif direction.y > 0:
			$AnimationPlayer.play("18_down")
		elif direction.y < 0:
			$AnimationPlayer.play("18_up")
	last_dir = direction	
	pass
